'''
 Copyright ImJingLan 2020

 Bilibili API copyrighted Bilibili.com

 Dev Time:2021\07\27

'''
import json
import requests
import os
import re

def mkcoverdir(PATH):#新建文件夹
    if not os.path.isdir(PATH):
        os.mkdir(PATH)

def imgdownload(url,name): #封面下载
    cover = requests.get(url)
    with open('./'+name+'/cover.jpg', 'wb') as pic:
        pic.write(cover.content)

def av2bv(av):#AV号转BV号
    info = requests.get('https://api.bilibili.com/x/web-interface/view?aid='+av).text
    info = json.loads(info)
    if info.get('code') == 0:
        vid = info['data'].get('bvid') # 返回的正确格式BV号
        return vid
    else:
        print("找不到该AV号")
        print("CODE:"+str(info.get('code'))+" MESSAGE:"+info.get('message'))#服务器返回无视频消息
        return 1

def bvcheck(vid):#检查BV号是否合法
    if vid.startswith('BV',0,2) or vid.startswith('bV',0,2) or vid.startswith('Bv',0,2) or vid.startswith('bv',0,2):# 硬检测是否为BV开头
        if len(vid) == 12:
            info = info = requests.get('https://api.bilibili.com/x/web-interface/view?bvid='+vid).text
            info = json.loads(info)
            if info.get('code') == 0:
                return True
            else:
                print("找不到该BV号")
                print("CODE:"+str(info.get('code'))+" MESSAGE:"+info.get('message'))
                return False
                

        else:
            print('这不是一个合法的BV号, BV号应为12位字符串')
            return False
    else:
        print('这不是一个合法的BV号，BV号应为 BV 开头')
        return False

def copyright(x): # 是否为原创
    if x==1:
        return "是"
    else:
        return "否"

def videoinfo(info,name): # 解析视频信息
    f = open('./'+name+'/info.txt','w' ,encoding='utf-8')
    print(info['data'].get('title')+"\n", file=f)

    print('播放量: '+str(info['data']['stat'].get("view"))+"\n", file=f)

    print('弹幕: '+str(info['data']['stat'].get("danmaku"))+"条\n", file=f)
    print('点赞: '+str(info['data']['stat'].get("like"))+"次\n", file=f)
    print('硬币: '+str(info['data']['stat'].get("coin"))+"个\n", file=f)
    print('收藏人数: '+str(info['data']['stat'].get("favorite"))+"人\n", file=f)

    print('分享: '+str(info['data']['stat'].get("share"))+"次\n", file=f)
    print("类型: "+info["data"].get("tname")+"\n", file=f)

    print("是否原创: "+copyright(info["data"].get("copyright"))+"\n", file=f)

    print("视频最高分辨率: "+str(info['data']["dimension"].get("width"))+"x"+str(info['data']["dimension"].get("height"))+"\n", file=f)

    desc = info["data"].get('desc')
    desc = desc.replace("\r","\n")

    print("简介:\n"+desc+"\n", file=f )

    if info['data'].get('staff'):
        print("是否联合投稿: 是\n", file=f)
        staff=info['data']['staff']
        maxlen = len(staff)
        print("Staffs:\n", file=f)
        for i in range(maxlen):
            print("    "+staff[i].get('title')+": "+staff[i].get('name')+"\n", file=f)
    else:
        print("是否联合投稿: 否\n", file=f)
        if info['data']['owner']:
            print('UP主: '+ info['data']['owner'].get('name'), file=f)
    f.close


def main():
    valid = True
    print("请选择 AV号 / BV号")
    print("1.AV号     2.BV号")
    status = input()

    if status == '1':
        vid = input('AV号:')
        vid = re.sub('av', '', vid, flags=re.IGNORECASE)
        if vid.isdigit():
            vid = av2bv(vid)
            if vid == 1:
                valid = False
        else:
            print('这不是一个合法的AV号')
            valid = False

    if status == '2':
        vid = input('视频BV号:')#获取视频BV号
    
    if status == '1' or status == '2':
        if valid:
            if bvcheck(vid):
                info = requests.get('https://api.bilibili.com/x/web-interface/view?bvid='+vid).text
                info = json.loads(info)
                bvid = info['data'].get('bvid') # 返回的正确格式BV号
                cover = info['data'].get('pic') # 封面地址d
                title = info['data'].get('title') # 视频标题
                if status == '1':
                    vid = "av"+str(info['data'].get('aid')) #返回的正确格式BV号
                if status == '2':
                    vid = info['data'].get('bvid') # 返回的正确格式BV号
                mkcoverdir(title+' - '+vid)
            #   print(title+' - '+bvid+": "+cover)

                videoinfo(info,title+' - '+vid)
                print('完成!') # 提示一下
                print("保存目录: ./"+title+' - '+vid+"/")
                imgdownload(cover,title+' - '+vid) # 下载
                #print('https://api.bilibili.com/x/web-interface/view?bvid='+vid)
                
    else:
        print("这不是一个合法的状态码")


# 主程序
if __name__ == "__main__":
    main()
    os.system('pause')